<template>
  <div class="app-container">
    <el-card class="operate-container" shadow="never">
      <el-form :inline="true" class="demo-form-inline">
        <el-form-item label="用户名">
          <el-input v-model="searchObj.username" placeholder="用户名" size="mini"></el-input>
        </el-form-item>
        <el-form-item label="姓名" style="margin-left: 20px;">
          <el-input v-model="searchObj.name" placeholder="姓名" size="mini"></el-input>
        </el-form-item>
        <el-form-item label="状态" style="margin-left: 20px;">
          <el-select v-model="searchObj.status" placeholder="状态" size="mini">
            <el-option label="有效" value="1"></el-option>
            <el-option label="无效" value="0"></el-option>
          </el-select>
        </el-form-item>
        <br/>
        <el-form-item label="创建时间">
          <el-date-picker v-model="searchObj.beginTime" placeholder="开始时间" size="mini"
            value-format="yyyy-MM-dd HH:mm:ss"></el-date-picker>
        </el-form-item>
        <el-form-item label="-">
          <el-date-picker v-model="searchObj.endTime" placeholder="结束时间" size="mini"
            value-format="yyyy-MM-dd HH:mm:ss"></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="fetchData">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="default" icon="el-icon-refresh-right" size="mini" @click="resetData">清空</el-button>
        </el-form-item>
      </el-form>
      <!-- 工具按钮 -->
      <div style="display: flex;">
      <el-button size="mini" class="btn-add" type="primary"  @click="openDialogForm()" style="margin-left: 10px;" v-if="$hasBP('bnt.sysUser.add')">添加</el-button>
      <el-button size="mini" class="btn-add" type="danger" @click="batchRemove()" v-if="$hasBP('bnt.sysUser.remove')">批量删除</el-button>
      <!-- <el-button size="mini" class="btn-add" type="warning" @click="exportUserInfoExcel()" v-if="$hasBP('bnt.sysUser.export')">导出</el-button> -->
      <el-upload
          :show-file-list="false"
          :headers="token"
          :on-success="onUploadSuccess"
          :on-error="onUploadError"
          action="http://localhost:8888/system/user/importUserInfoExcel"
          class="upload-demo">
        <el-button size="mini" type="warning" style="margin-left:20px" v-if="$hasBP('bnt.sysUser.import')">导入</el-button>
      </el-upload>
      <a v-if="$hasBP('bnt.sysUser.export')" style="text-decoration: none;background: #f5913f;color: #fff;padding: 7px 20px 0px 20px;font-size: 5px;margin-left: 10px;border-radius: 10%;" @click="exportUserInfoExcel()">导出</a>
    </div>
    </el-card>
    <el-table :data="list" stripe border
      @selection-change="handleSelectionChange">
      <el-table-column type="selection"/>
      <el-table-column label="序号" width="50">
        <template slot-scope="scope">
          {{ (pageNum - 1) * pageSize + scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column prop="username" label="用户名" width="120" align="center"> </el-table-column>
      <el-table-column prop="name" label="姓名" width="100" align="center"> </el-table-column>
      <el-table-column prop="status" label="状态" width="100" align="center">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status === 1"
            @change="switchStatus(scope.row)">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column prop="gender" label="性别" width="80"  align="center">
        <template slot-scope="scope">
          <el-tag :type="primary" :size="mini" disable-transitions>{{ scope.row.gender===1?'男':'女' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="phone" label="手机号" width="150" align="center"> </el-table-column>
      <el-table-column prop="email" label="邮箱" width="150" align="center"> </el-table-column>
      <el-table-column prop="createTime" label="创建时间"  width="180" sortable :formatter="dateFormat"> </el-table-column>
      <el-table-column prop="updateTime" label="修改时间" width="180" sortable :formatter="dateFormat"> </el-table-column>
      <el-table-column prop="description" label="备注" width="200"> </el-table-column>
      <el-table-column label="操作" align="center" fixed="right" width="180">
        <template slot-scope="scope">
          <span style="font-size: 8px;color: #429ec9;cursor: pointer;" @click="openDialogForm(scope.row.id)" v-if="$hasBP('bnt.sysUser.update')">修改</span>
          <span style="font-size: 8px;color: #429ec9;margin-left: 10px;cursor: pointer;" @click="removeById(scope.row.id)" v-if="$hasBP('bnt.sysUser.remove')">删除</span>
          <span style="font-size: 8px;color: #429ec9;margin-left: 10px;cursor: pointer;" @click="showAssignRole(scope.row)" v-if="$hasBP('bnt.sysUser.assignRole')">分配角色</span>
          <!-- <el-button type="primary" icon="el-icon-edit" circle @click="openDialogForm(scope.row.id)" v-if="$hasBP('bnt.sysUser.update')" ></el-button> -->
          <!-- <el-button type="danger" icon="el-icon-delete" circle @click="removeById(scope.row.id)" v-if="$hasBP('bnt.sysUser.remove')"></el-button> -->
          <!-- <el-button type="warning" icon="el-icon-share" circle @click="showAssignRole(scope.row)" v-if="$hasBP('bnt.sysUser.assignRole')"></el-button> -->
        </template>
      </el-table-column>
    </el-table>
     <!-- 分页组件 -->
     <el-pagination :current-page="pageNum" :total="total" :page-size="pageSize"
      :page-sizes="[5, 10, 20, 30, 40, 50, 100]" style="padding: 30px 0; text-align: center;"
      layout="total,sizes,prev, pager, next, jumper" @size-change="changePageSize" @current-change="changeCurrentPage">
    </el-pagination>
    <!-- 添加修改弹出框 -->
    <el-dialog :title="dialogFormTitle" :visible.sync="dialogFormVisible" top="20px" width="500px" @close="resetForm('form')">
      <el-form :model="form"  :rules="rules" ref="form" >
        <el-form-item label="用户名" :label-width="formLabelWidth" prop="username">
          <el-input v-model="form.username" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码" :label-width="formLabelWidth" prop="password" v-if="passwordVisible">
          <el-input v-model="form.password" autocomplete="off" type="password"></el-input>
        </el-form-item>
        <el-form-item label="姓名" :label-width="formLabelWidth" prop="name">
          <el-input v-model="form.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="性别" :label-width="formLabelWidth">
          <el-radio v-model="form.gender" label="1">男</el-radio>
          <el-radio v-model="form.gender" label="0">女</el-radio>
        </el-form-item>
        <el-form-item label="状态" :label-width="formLabelWidth">
          <el-switch
            v-model="status"
            active-color="#13ce66"
            inactive-color="#ff4949">
          </el-switch>
        </el-form-item>
        <el-form-item label="手机号" :label-width="formLabelWidth">
          <el-input v-model="form.phone" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" :label-width="formLabelWidth">
          <el-input v-model="form.email" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="备注" :label-width="formLabelWidth" prop="description">
          <el-input v-model="form.description" autocomplete="off" type="textarea" :rows="3"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="resetForm('form')">取 消</el-button>
        <el-button type="primary" @click="addOrUpdate('form')">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="分配角色" :visible.sync="dialogAssignVisible" width="500px" @close="resetAssign('form')">
      <el-form label-width="80px">
        <el-form-item label="用户名：">
          {{form.username}}
        </el-form-item>
        <el-form-item label="角色列表">
          <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
          <div style="margin: 15px 0;"></div>
          <el-checkbox-group v-model="userRoleIds" @change="handleCheckedChange">
            <el-checkbox v-for="role in allRoles" :key="role.id" :label="role.id">{{role.roleName}}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="resetAssign('form')">取 消</el-button>
        <el-button type="primary" @click="assignRole()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import sysUserApi from "@/api/system/sysUser";
import store from '@/store'
import axios from "axios";
import moment from "moment"
export default {
  data(){
    return{
      searchObj: {}, // 查询表单对象
      list: [], //用户列表
      total: 0, //总记录数
      pageNum: 1, //页码
      pageSize: 10, //每页记录数
      multipleSelection: [], //批量删除选中的记录列表
      dialogFormVisible: false,  //添加修改弹出框
      dialogAssignVisible: false,
      formLabelWidth: '100px',
      dialogFormTitle: '',
      status: false,
      passwordVisible: false,
      isIndeterminate: false,
      checkAll: false,
      allRoles: [], // 所有角色列表
      userRoleIds: [], // 用户的角色ID的列表
      dialogImportVisible: false,
      form:{
        username: '',
        password: '',
        name: '',
        gender: '',
        status: 0,
        phone: '',
        email: '',
        description: ''
      },
      rules: {
          username: [
            { required: true, message: '请输入用户名', trigger: 'blur' },
            { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
          ],
          password: [
            { required: true, message: '请输入密码', trigger: 'blur' },
            { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
          ],
          name: [
            { required: true, message: '请输入姓名', trigger: 'blur' },
            { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
          ],
          description: [
            { max: 500, message: '长度在500 个字符之内', trigger: 'blur' }
          ]
        }
    }
  },
  created() {
    //页面渲染之前
    this.fetchData();
  },
  methods: {
    /*日期处理*/
    dateFormat:function(row,column){
      var date = row[column.property];
      if(date === undefined){
        return ''
      }
      return moment(date).format("YYYY-MM-DD HH:mm:ss")
    },
    importData() {
      this.dialogImportVisible = true
    },
    onUploadError(response,file){
      console.log(response);
      this.$message.info("上传失败")
      this.dialogImportVisible = false
      this.fetchData()
    },
    onUploadSuccess(response, file) {
      if(response.code !== 20000){
        this.$message.warning(response.message)
      }else{
        this.$message.success('上传成功')
      }
      this.dialogImportVisible = false
      this.fetchData()
    },
    //导出
    exportUserInfoExcel(){
      let token = store.getters.token
      console.log(token);
      axios({
        method: "get",
        url: "http://localhost:8888/system/user/exportUserInfoExcel",
        headers: {
          'Access-Token': token,
        },
        responseType: 'blob'
      }).then(res =>{
        const link=document.createElement('a');
            try {
              let blob = new Blob([res.data]);
              link.style.display='none';
              // 兼容不同浏览器的URL对象
              const url = window.URL || window.webkitURL || window.moxURL;
              link.href=url.createObjectURL(blob);
              link.setAttribute('download', "用户信息.xlsx");
              document.body.appendChild(link);
              link.click();
              document.body.removeChild(link);
              url.revokeObjectURL(link.href);//销毁url对象
            }catch (e) {
              console.log('下载的文件出错',e)
            }
      })
      // window.open("http://localhost:8888/system/user/exportUserInfoExcel")
    },
    /*
    全选勾选状态发生改变的监听
    */
    handleCheckAllChange (value) {// value 当前勾选状态true/false
      // 如果当前全选, userRoleIds就是所有角色id的数组, 否则是空数组
      this.userRoleIds = value ? this.allRoles.map(item => item.id) : []
      // 如果当前不是全选也不全不选时, 指定为false
      this.isIndeterminate = false
    },
    /*
    角色列表选中项发生改变的监听
    */
    handleCheckedChange (value) {
      const {userRoleIds, allRoles} = this
      this.checkAll = userRoleIds.length === allRoles.length && allRoles.length>0
      this.isIndeterminate = userRoleIds.length>0 && userRoleIds.length<allRoles.length
    },
    showAssignRole(row){
      this.form = row
      this.dialogAssignVisible = true
      sysUserApi.toAssign(row.id)
      .then(response =>{
        this.allRoles = response.data.allRoles
        this.userRoleIds = response.data.userRoleIds
        this.checkAll = this.allRoles.length === this.userRoleIds.length
        this.isIndeterminate = this.userRoleIds.length > 0 && this.userRoleIds.length < this.allRoles.length
      })
    },
    assignRole(){
      let assignRoleVO = {
        userId: this.form.id,
        userRoleIds: this.userRoleIds
      }
      console.log(assignRoleVO);
      sysUserApi.doAssign(assignRoleVO)
      .then(response =>{
        this.$message({
          type: 'success',
          message: '分配角色成功!'
        });
        this.dialogAssignVisible = false
        this.fetchData()
      })
    },
    switchStatus(row){
      row.status = row.status === 1?0:1
      sysUserApi.updateUserStatus(row.id,row.status)
      .then(response =>{
        this.$message({
          type: 'success',
          message: '操作成功!'
        });
        //刷新
        this.fetchData()
      })
    },
    //批量删除
    batchRemove(){
      //判断非空
      if(this.multipleSelection.length===0){
        this.$message.warning('请选择要删除的记录！')
        return
      }
      this.$confirm('此操作将永久删除该信息, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          var idList =[]
          //遍历数组
          this.multipleSelection.forEach(item => {
            idList.push(item.id)
          })
          sysUserApi.batchRemove(idList)
          .then((response) => {
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
            //刷新
            this.fetchData()
          })
        });

    },
    //复选框发生变化
    handleSelectionChange(selection){
      this.multipleSelection = selection
      console.log(this.multipleSelection)
    },
    openDialogForm(userId){
      if(userId == undefined){
        this.passwordVisible = true
        this.dialogFormTitle = "添加用户"
      }else{
        this.passwordVisible = false
        this.dialogFormTitle = "修改用户"
        sysUserApi.getUserById(userId)
        .then(response =>{
          this.form = response.data
          this.form.gender = String(response.data.gender)
          console.log(this.form);
          this.status = this.form.status == 1 ? true : false
        })
      }
      this.dialogFormVisible = true
    },
    //添加修改表单
    addOrUpdate(formName){
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if(this.status){
            this.form.status = 1
          }else{
            this.form.status = 0
          }
          if(this.form.id == undefined || this.form.id == ''){
            sysUserApi.saveUser(this.form)
            .then(response =>{
              this.$message({
                type: 'success',
                message: '添加成功!'
              });
              this.dialogFormVisible = false
              //刷新
              this.fetchData()
            })
          }else{
            sysUserApi.updateUser(this.form)
            .then(response =>{
              this.$message({
                type: 'success',
                message: '修改成功!'
              });
              this.dialogFormVisible = false
              //刷新
              this.fetchData()
            })
          }
          
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    
    },
    resetForm(form){
      this.$refs[form].resetFields();
      this.form= {}
      this.dialogFormVisible = false
    },
    resetAssign(form){
      this.form = {}
      this.dialogAssignVisible = false
    },

    fetchData() {
      sysUserApi
        .getSysUserPageList(this.pageNum, this.pageSize, this.searchObj)
        .then((response) => {
          this.list = response.data.records;
          this.total = response.data.total;
        });
    },
    //改变每页显示记录数
    changePageSize(size) {
      this.pageSize = size;
      this.fetchData();
    },
    //改变页码数
    changeCurrentPage(page) {
      this.pageNum = page;
      this.fetchData();
    },

    resetData() {
      this.searchObj = {}
      this.fetchData()
    },
    //删除单条信息
    removeById(id){
      this.$confirm('此操作将永久删除该条信息, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          sysUserApi.removeUserId(id)
          .then((response) => {
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
            //刷新
            this.fetchData()
          })
        });
    }

  },
  computed:{
    token(){
      return {"Access-Token":store.getters.token}
    }
  }
}
</script>

<style>

</style>